package com.simple.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.simple.entity.CodeResult;
import com.simple.entity.SysUser;
import com.simple.service.SysUserService;
import com.simple.utils.EncryptionUtils;

@Controller
public class RegisterController {
	
	private static final Logger logger = LoggerFactory.getLogger(RegisterController.class);
	
	@Autowired
	SysUserService sysUserService;
	

	@RequestMapping("/register.html")
	public String register() {
		return "register";
	}
	
	/**
	 * 验证用户名
	 * @param username 用户名
	 * 
	 * */
	@RequestMapping("/usernameCheck.html")
	@ResponseBody
	public CodeResult usernameCheck(String username) {
		SysUser user=sysUserService.selectUserName(username);
		return CodeResult.customResult(user);
	}
	
	/**
	 * 验证邮箱
	 * @param email 输入的邮箱
	 * 
	 * */
	@RequestMapping("/emailCheck.html")
	@ResponseBody
	public CodeResult emailCheck(String email) {
		SysUser user=sysUserService.selectEmail(email);
		return CodeResult.customResult(user);
	}
	
	/**
	 * 注册提交
	 * @param sysUser实体
	 * 
	 * */
	@RequestMapping("/registerSubmit.html")
	@ResponseBody
	public CodeResult registerSubmit(SysUser sysUser,HttpServletRequest request) {
		//保存信息
		sysUserService.save(sysUser);
		//发送邮件
		sysUserService.sendMail(sysUser, request);
		return CodeResult.success();
	}
	
	/**
	 * 账户激活
	 * @param sign 获取地址栏参数
	 * 
	 * */
	@RequestMapping("/activation.html")
	public String activationAccount(HttpServletRequest request,Model model) {
		String param=request.getParameter("sign");
		//获取当前邮箱
		String mail=EncryptionUtils.decryptBase64(param,"daliang9527");
		logger.info("-->地址栏解密获取邮箱："+mail);
		//查询数据库 返回
		SysUser user=sysUserService.selectEmail(mail);
		if(null!=user) {
			if(user.getStatus()==0) {
				user.setStatus(1);
				sysUserService.saveAndFlush(user);
				model.addAttribute("status", "1");
			}else {
				model.addAttribute("status", "2");
			}
		}else {
			model.addAttribute("status", "3");//激活失败
		}
		return "activation";
	}
	
}
